package com.zhenyi.liuxue.admin;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.liuxue.common.model.LxCnSchool;
import com.liuxue.common.model.LxMajor;
import com.liuxue.common.model.LxSchool;
import com.liuxue.common.model.LxSchoolRank;
import com.liuxue.common.model.LxUkSchool;

public class SchoolController extends AdminController {

	@Override
	public void list() {
		// Kv kv = Kv.create();
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindUkSchool");
		Page<LxUkSchool> pages = LxUkSchool.dao.paginate(getPage(), getPageSize(), sqlPara);
		
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		render("/lx/admin/ukSchools/index.html");
	}
	
	public void info() {
		Long ukSchoolId = getParaToLong("ukSchoolId");
		if (ukSchoolId != null) {
			LxUkSchool ukSchool = LxUkSchool.dao.findById(ukSchoolId);
			if (ukSchool == null || (ukSchool.getFlag() != null && ukSchool.getFlag().equals(1))) {
				renderFailure(404, "invalid id");
				return;
			}
			LxSchool school = LxSchool.dao.searchFirst("unionSchoolId", ukSchool.getUnionSchoolId());
			setAttr("ukSchool", JsonKit.toJson(ukSchool));
			setAttr("school", JsonKit.toJson(school));
			
			Kv kv = Kv.create();
			kv.set("ukSchoolId", ukSchoolId);
			SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindMajors", kv);
			List<LxMajor> majors = LxMajor.dao.find(sqlPara);
			setAttr("majors", JsonKit.toJson(majors));
		}
		render("/lx/admin/ukSchools/info.html");
	}

	@Override
	public void submit() {
		Long id = getParaToLong("id");
		String name = getPara("name");
		String engName = getPara("engName");
		String cover = getPara("cover");
		String logo = getPara("logo");
		String images = getPara("images");
		String video = getPara("video");
		String intro = getPara("intro");
		String appleTime = getPara("appleTime");
		String fee = getPara("fee");
		String city = getPara("city");
		String teacherRate = getPara("teacherRate");
		String sexRate = getPara("sexRate");
		String internationalStudentRate = getPara("internationalStudentRate");
		String rates = getPara("rates");
		String advantageMajors = getPara("advantageMajors");
		String requirement = getPara("requirement");
		String dataFrom = getPara("dataFrom");
		Long sort = getParaToLong("sort", 99999L);
		
		LxSchool school = LxSchool.dao.findById(id);
		if (school == null) {
			LxUkSchool ukSchool = new LxUkSchool();
			ukSchool.setName(name);
			ukSchool.setIntro(intro);
			ukSchool.setLogo(logo);
			ukSchool.setAddress(city);
			ukSchool.setEngName(engName);
			ukSchool.setSort(sort);
			ukSchool.setMinRank(999);
			ukSchool.setScore(80);
			ukSchool.setMaxRank(1);
			ukSchool.save();
			ukSchool.setUnionSchoolId(ukSchool.getId());
			ukSchool.update();
			
			school = new LxSchool();
			school.setUnionSchoolId(ukSchool.getId());
			school.save();
		} else {
			List<LxUkSchool> ukSchools = LxUkSchool.dao.search("unionSchoolId", school.getUnionSchoolId());
			for (LxUkSchool ukSchool : ukSchools) {
				ukSchool.setName(name);
				ukSchool.setIntro(intro);
				ukSchool.setLogo(logo);
				ukSchool.setAddress(city);
				ukSchool.setEngName(engName);
				ukSchool.setSort(sort);
				ukSchool.update();
			}
		}
		school.setName(name);
		school.setEngName(engName);
		school.setCover(cover);
		school.setLogo(logo);
		school.setImages(images);
		school.setVideo(video);
		school.setIntro(intro);
		school.setAppleTime(appleTime);
		school.setFee(fee);
		school.setCity(city);
		school.setTeacherRate(teacherRate);
		school.setSexRate(sexRate);
		school.setInternationalStudentRate(internationalStudentRate);
		school.setRates(rates);
		school.setAdvantageMajors(advantageMajors);
		school.setRequirement(requirement);
		school.setSort(sort.intValue());
		school.setDataFrom(dataFrom);
		school.update();
		
		renderSuccess();
	}
	
	public void delete() {
		Long ukSchoolId = getParaToLong("ukSchoolId");
		if (ukSchoolId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxUkSchool info = LxUkSchool.dao.findById(ukSchoolId);
		if (info == null) {
			renderFailure(404, "ukSchool not found. invailid id");
			return;
		}
		info.setFlag(1);
		renderFlag(info.update());
	}
	
	public void categories() {
		Long ukSchoolId = getParaToLong("ukSchoolId");
		Integer rank = getParaToInt("rank");
		String department = getPara("department");
		if (ukSchoolId == null) {
			renderFailure(500, "ukschool id is null");
			return;
		}
		if (StrKit.isBlank(department)) {
			renderFailure(500, "department is required");
			return;
		}
		LxUkSchool ukSchool = LxUkSchool.dao.findById(ukSchoolId);
		LxSchool school = LxSchool.dao.searchFirst("unionSchoolId", ukSchool.getUnionSchoolId());
		
		Kv kv = Kv.create();
		kv.set("schoolId", school.getId());
		kv.set("department", department);
		if (rank != null) {
			kv.set("rank", rank);
		}
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindSchoolCategories", kv);
		List<Record> list = Db.use("liuxue").find(sqlPara);
		ArrayList<String> result = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			if (StrKit.notBlank(list.get(i).getStr("category"))) {
				result.add(list.get(i).getStr("category"));
			}
		}
		renderResult(result);
	}
	
	public void majorList() {
		Long ukSchoolId = getParaToLong("ukSchoolId");
		String keyword = getPara("keyword");
		String rank = getPara("rank");
		String department = getPara("department");
		String category = getPara("category");
		if (ukSchoolId == null) {
			renderFailure(500, "ukschool id is null");
			return;
		}
		LxUkSchool ukSchool = LxUkSchool.dao.findById(ukSchoolId);
		LxSchool school = LxSchool.dao.searchFirst("unionSchoolId", ukSchool.getUnionSchoolId());
		
		Kv kv = Kv.create();
		kv.set("ukSchoolId", ukSchoolId);
		if (StrKit.notBlank(keyword)) {
			kv.set("keyword", keyword);
			setAttr("keyword", keyword);
		}
		if (StrKit.notBlank(rank)) {
			kv.set("rank", rank);
			setAttr("rank", rank);
		}
		if (StrKit.notBlank(department)) {
			kv.set("department", department);
			setAttr("department", department);
		}
		if (StrKit.notBlank(category)) {
			kv.set("category", category);
			setAttr("category", category);
		}
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindMajor", kv);
		Page<LxMajor> pages = LxMajor.dao.paginate(getPage(), getPageSize(), sqlPara);
		
		Kv kv2 = Kv.create();
		kv2.set("schoolId", school.getId());
		SqlPara sqlPara2 = Db.use("liuxue").getSqlPara("LXFindSchoolDepartments", kv2);
		List<Record> departmentList = Db.use("liuxue").find(sqlPara2);
		String[] departments = new String[departmentList.size()];
		for (int i = 0; i < departmentList.size(); i++) {
			departments[i] = departmentList.get(i).getStr("department");
		}
		setAttr("departments", JsonKit.toJson(departments));
		
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		setAttr("ukSchoolId", ukSchoolId);
		setAttr("schoolName", ukSchool.getName());
		render("/lx/admin/ukSchools/majorList.html");
	}
	
	public void majorInfo() {
		setReferer();
		Long majorId = getParaToLong("majorId");
		Long ukSchoolId = getParaToLong("ukSchoolId");
		if (ukSchoolId == null) {
			renderFailure(500, "uk school id is null");
			return;
		}
		LxUkSchool ukSchool = LxUkSchool.dao.findById(ukSchoolId);
		LxSchool school = LxSchool.dao.searchFirst("unionSchoolId", ukSchool.getUnionSchoolId());
		
		if (majorId != null) {
			LxMajor info = LxMajor.dao.findById(majorId);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}
			setInfoItem(JsonKit.toJson(info));
		}
		setAttr("schools", JsonKit.toJson(LxSchool.dao.findAll()));
		setAttr("schoolId", school.getId());
		render("/lx/admin/ukSchools/majorInfo.html");
	}
	
	public void submitMajor() {
		Long majorId = getParaToLong("majorId");
		Long schoolId = getParaToLong("schoolId");
		String name = getPara("name");
		String englishName = getPara("englishName");
		Integer rank = getParaToInt("rank");
		String department = getPara("department");
		String category = getPara("category");
		String term = getPara("term");
		String fee = getPara("fee");
		String coreClass = getPara("coreClass");
		String requirement = getPara("requirement");
		String development = getPara("development");
		String keywords = getPara("keywords");
		if (schoolId == null) {
			renderFailure(500, "school id is null");
			return;
		}
		LxMajor info = null;
		if (majorId == null) {
			info = new LxMajor();
			info.setSchoolId(schoolId);
			info.setVisitCount(0);
			info.save();
		} else {
			info = LxMajor.dao.findById(majorId);
			if (info == null) {
				renderFailure(404, "not found");
				return;
			}
		}
		info.setName(name);
		info.setEnglishName(englishName);
		info.setRank(rank);
		info.setDepartment(department);
		info.setCategory(category);
		info.setTerm(term);
		info.setFee(fee);
		info.setCoreClass(coreClass);
		info.setRequirement(requirement);
		info.setDevelopment(development);
		info.setKeywords(keywords);
		renderFlag(info.update());
	}
	
	public void deleteMajor() {
		Long majorId = getParaToLong("majorId");
		if (majorId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxMajor info = LxMajor.dao.findById(majorId);
		if (info == null) {
			renderFailure(404, "not found");
			return;
		}
		renderFlag(info.delete());
	}

	public void cnSchoolList() {
		String keyword = getPara("keyword");
		String from = "FROM lx_cn_school";
		String totalRowSql = "SELECT count(*) " + from;
		String findSql = null;
		String where = " WHERE lx_cn_school.name LIKE '%" + keyword + "%'";
		String orderBy = " ORDER BY convert(lx_cn_school.`name` using gbk) ASC";
		if (StrKit.isBlank(keyword)) {
			findSql = "SELECT lx_cn_school.* " + from + orderBy;
		} else {
			totalRowSql += where;
			
			findSql = "SELECT lx_cn_school.* " + from + where + orderBy;
			setAttr("keyword", keyword);
		}
		Page<LxCnSchool> pages = LxCnSchool.dao.paginateByFullSql(getPage(), PAGE_SIZE, totalRowSql, findSql);
		
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		render("/lx/admin/cnSchools/index.html");
	}
	
	public void cnSchoolInfo() {
	}
	
	public void submitCnSchool() {
		Long cnSchoolId = getParaToLong("cnSchoolId");
		String name = getPara("name");
		if (StrKit.isBlank(name)) {
			renderMsg("请输入大学名称");
			return;
		}
		LxCnSchool cnSchool = null;
		if (cnSchoolId != null) {
			cnSchool = LxCnSchool.dao.findById(cnSchoolId);
			if (cnSchool == null) {
				renderFailure(404, "not found");
				return;
			}
		} else {
			cnSchool = new LxCnSchool();
			cnSchool.save();
		}
		cnSchool.setName(name);
		cnSchool.update();
		renderSuccess();
	}
	
	public void deleteCnSchool() {
		Long cnSchoolId = getParaToLong("cnSchoolId");
		if (cnSchoolId == null) {
			renderFailure(500, "id is null");
			return;
		}
		LxCnSchool info = LxCnSchool.dao.findById(cnSchoolId);
		if (info == null) {
			renderFailure(404, "cnSchool not found. invailid id");
			return;
		}
		boolean flag = info.delete();
		if (flag) {
			// 清除外键
			Kv kv = Kv.create();
			kv.set("cnSchoolId", cnSchoolId);
			SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXAdminFindSchoolRankByCn", kv);
			List<LxSchoolRank> list = LxSchoolRank.dao.find(sqlPara);
			for (LxSchoolRank record : list) {
				record.delete();
			}
		}
		renderFlag(flag);
	}

}
